/**
 * 入参
    type： 1- 指令   2-簿记
    onOk：指令下达成功或簿记成功抛出事件
    onCancel：取消抛出事件

*/
import React, { PureComponent } from 'react';
import { AvailableAssetC, TradeHoldC, FirstHeaderC } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Tabs } from 'antd';
import style from './index.less';
import config from './config';
import HeaderInfoC from './headerInfo';
import BondInfoC from './bondInfo';
import DaZongBondC from './daZongBond/index';
import DaZongBondC2 from './daZongBond2/index';
import Trade0 from '../TradForm1/ZqTradingCode/index'; // 交易所债券指令
import Trade1 from '../TradForm1/bankBond/index'; //
import Trade2 from '../TradForm1/SjExchangeStock/index';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import VirtualTarget from './VirtualTarget';
import lodash from 'lodash';
const { TabPane } = Tabs;
@Form.create()
@connect(({ isAccountConfiguredM }) => ({ isAccountConfiguredM }))
export default class AddBond extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      timeStamp: new Date().getTime(), //时间戳
      money: {}, //可用金额，
      position: {}, //可用数量
      activeKey: '0', //当前活跃的tab
      portfolio: undefined, //当前组合
      tradingcode: undefined, //当前证券代码 {exchangecode: "101", tradingcode: "510060", secuabbr: "上证中央企业50ETF"}
      portfolio0: undefined, //交易所组合id
      portfolio1: undefined, //银行间组合id
      portfolio2: undefined, //上交所组合id
      portfolio3: undefined, //大宗现券组合id
      tradingcode0: undefined, //交易所证券代码id
      tradingcode1: undefined, //银行间证券代码id
      tradingcode2: undefined, //上交所证券代码id
      tradingcode3: undefined, //大宗现券证券代码id
      isCanOrder: true, //是否配置
      productGroupId: undefined, //产品组id
    };
  }

  componentDidMount() {}

  //tab切换 判断组合id
  tabChange = (key, type) => {
    let temp = `${type}${key}`;
    if (JSON.stringify(this.state[temp]) !== JSON.stringify(this.state[type])) {
      //判断当前组合或证券代码 是否激活的tab下的一致，不一致则更新
      this.setState({
        [type]: this.state[temp],
      });
    }
  };
  //组合变更id 切换
  portfolioOnChange = (e, key) => {
    let temp = `portfolio${key}`;
    this.setState({
      [temp]: e,
    });
    if (e && this.props.type == 1) {
      //新增指令时 需要判断该组合是否进行了指令配置
      this.props.dispatch({
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: e,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else if (!e && this.props.type == 1) {
      this.setState({
        isCanOrder: true,
      });
    }
    if (this.state.portfolio !== e) {
      //组合id不同则变更当前页面组合id
      this.setState({
        portfolio: e,
      });
    }
  };
  //证券代码变更
  tradingcodeOnChange = (e, key) => {
    const { type } = this.props;
    if (type == 10) {
      return;
    }
    let temp = `tradingcode${key}`;
    this.setState({
      [temp]: e,
    });
    if (this.state.tradingcode !== e) {
      //证券代码不同则变更当前页面证券代码
      this.setState({
        tradingcode: e,
      });
    }
  };
  // 系列产品变更
  seriesProductsOnChange = (e, key) => {};
  // 产品组变更
  productGroupOnChange = (e) => {
    if (this.state.productGroupId != e?.key) {
      this.setState({
        productGroupId: e?.key,
      });
    }
  };
  //簿记成功、存续管理、多基金、组合试算之后调用
  onOk = () => {
    const { type } = this.props;
    if (type == 2 || type == 10 || type == 11 || type == 12) {
      this.props.onOk();
    }
  };
  //点击取消按钮
  onCancel = () => {
    const { type } = this.props;
    if (type == 2 || type == 10 || type == 11 || type == 12) {
      this.props.onCancel();
    }
    if (type == 1) {
      this.setState({
        isCanOrder: true,
      });
    }
  };
  showInfo() {
    const { activeKey, isCanOrder } = this.state;
    const { type, listId, currentRouter } = this.props;
    const props = {
      type: type,
      listId: listId,
      onOk: () => {
        this.onOk();
      },
      onCancel: () => {
        this.onCancel();
      },
      money: this.state.money,
      position: this.state.position,
      isCanOrder: isCanOrder,
    };
    const initComp = (key) => {
      if (key === '0')
        return (
          <Trade0
            {...props}
            businessType={key}
            portfolioOnChange={(e) => {
              this.portfolioOnChange(e, key);
            }}
            tradingcodeOnChange={(e) => {
              this.tradingcodeOnChange(e, key);
            }}
            seriesProductsOnChange={(e) => this.seriesProductsOnChange(e, key)}
          />
        );
      if (key === '1')
        return (
          <Trade1
            {...props}
            businessType={key}
            portfolioOnChange={(e) => {
              this.portfolioOnChange(e, key);
            }}
            tradingcodeOnChange={(e) => {
              this.tradingcodeOnChange(e, key);
            }}
            seriesProductsOnChange={(e) => this.seriesProductsOnChange(e, key)}
            productGroupOnChange={(e) => this.productGroupOnChange(e)}
          />
        );
      if (key === '2')
        return (
          <Trade2
            {...props}
            businessType={key}
            portfolioOnChange={(e) => {
              this.portfolioOnChange(e, key);
            }}
            tradingcodeOnChange={(e) => {
              this.tradingcodeOnChange(e, key);
            }}
          />
        );
      // 协商成交
      if (key === '3')
        return (
          <DaZongBondC
            {...props}
            businessType={key}
            portfolioOnChange={(e) => {
              this.portfolioOnChange(e, key);
            }}
            tradingcodeOnChange={(e) => {
              this.tradingcodeOnChange(e, key);
            }}
          />
        );
      //大宗现券
      if (key === '4')
        return (
          <DaZongBondC2
            {...props}
            businessType={'25'}
            portfolioOnChange={(e) => {
              this.portfolioOnChange(e, key);
            }}
            tradingcodeOnChange={(e) => {
              this.tradingcodeOnChange(e, key);
            }}
          />
        );
      // 虚拟标的 只在组合管理组合试算显示
      if (key === '5')
        return (
          <>
            <VirtualTarget
              {...props}
              businessType={'25'}
              portfolioOnChange={(e) => {
                this.portfolioOnChange(e, key);
              }}
              tradingcodeOnChange={(e) => {
                this.tradingcodeOnChange(e, key);
              }}
            />
          </>
        );
    };

    // 交易试算添加虚拟标的tab
    const tabs = lodash.cloneDeep(config.tabs);
    if (process.env.NODE_ENV === 'development') {
      if (currentRouter && currentRouter.indexOf('/portfolioBuild/portfolioTrial') !== -1) {
        tabs.unshift({
          key: '5',
          title: <span>虚拟标的</span>,
        });
      }
    } else {
      if (currentRouter && currentRouter.indexOf('/portfolioBuild/portfolioTrial') !== -1) {
        tabs.push({
          key: '5',
          title: <span>虚拟标的</span>,
        });
      }
    }

    return (
      <div className={'grayBg'}>
        <Tabs
          activeKey={activeKey}
          onChange={(val) => {
            this.setState(
              {
                activeKey: val,
              },
              () => {
                this.tabChange(val, 'portfolio');
                this.tabChange(val, 'tradingcode');
              },
            );
          }}
        >
          {tabs.map((item) => {
            if (this.props.type == 10 && item.key > 1) return null;
            if (this.props.type == 12 && item.key != 1) {
              this.setState({ activeKey: '1' });
              return null;
            }
            if (this.props.type == 1 && item.key == 1) {
              return null;
            }
            return (
              <TabPane tab={item.title} key={item.key}>
                {initComp(item.key)}
              </TabPane>
            );
          })}
        </Tabs>
      </div>
    );
  }
  render() {
    const { portfolio, tradingcode, productGroupId } = this.state;
    const { type } = this.props;
    return (
      <>
        {type != 10 ? (
          <div className={style.addBond}>
            <div>
              <HeaderInfoC bondID={tradingcode && tradingcode.secucode ? tradingcode.secucode : undefined} />
            </div>
            <div style={{ marginTop: '7px' }}>
              <div>
                <BondInfoC
                  bondID={tradingcode && tradingcode.secucode ? tradingcode.secucode : undefined}
                  tradingCode={tradingcode && tradingcode.tradingCode ? tradingcode.tradingCode : undefined}
                  exchangeCode={tradingcode && tradingcode.exchangeCode ? tradingcode.exchangeCode : undefined}
                />
              </div>
              <div>
                <div style={{ marginBottom: '14px' }}>
                  <AvailableAssetC
                    portfolio={portfolio}
                    productGroupId={productGroupId}
                    type={type}
                    onChange={(e) => {
                      this.setState({
                        money: e,
                      });
                    }}
                  />
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <TradeHoldC
                    // securityType={this.state.activeKey == '1' ? '0' : this.state.activeKey}
                    securityType={'0'}
                    portfolio={portfolio}
                    type={type}
                    productGroupId={productGroupId}
                    tradingcode={tradingcode && tradingcode.tradingCode ? tradingcode.tradingCode : undefined}
                    exchangecode={tradingcode && tradingcode.exchangeCode ? tradingcode.exchangeCode : undefined}
                    onChange={(e) => {
                      this.setState({
                        position: { ...e },
                      });
                    }}
                  />
                </div>
                <FirstHeaderC title={'交易要素'} />
                {this.showInfo()}
              </div>
            </div>
          </div>
        ) : (
          <div className={style.addBond}>{this.showInfo()}</div>
        )}
      </>
    );
  }
}
